package org.example.quartz.BIP;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.lang.UUID;
import cn.hutool.db.Entity;
import cn.hutool.db.Session;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.example.quartz.service.LogService;
import org.example.quartz.service.OrgService;
import org.example.quartz.service.SqlService;
import org.example.quartz.service.UtilService;
import org.example.quartz.task.QuartzTaskJob;
import org.example.quartz.util.DataSourceUtil;
import org.example.quartz.util.SafeStringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
// 再Job被执行结束后，将会更新JobDataMap，这样下次Job执行后悔使用新的值而不是初始值
@PersistJobDataAfterExecution
// 同一时间将只有一个Job实例被执行，为了避免并发问题导致数据紊乱，建议这两个注解一起使用
@DisallowConcurrentExecution
public class GLQuartz_BIP implements QuartzTaskJob {
    Map<String, Object> gsMap = DataSourceUtil.getGS();
    //全局接口配置
    String IP = (String) gsMap.get("IP");
    String PORT = (String) gsMap.get("PORT");
    String ECC = (String) gsMap.get("ECC");
    String Bearer = (String) gsMap.get("Bearer");
    //日志
    LogService loginfo = SpringUtil.getBean(LogService.class);
    //orgService
    OrgService orgService = SpringUtil.getBean(OrgService.class);
    //orgService
    UtilService utilService = SpringUtil.getBean(UtilService.class);
    SqlService sqlService = SpringUtil.getBean(SqlService.class);


    /**
     * 凭证接口
     * 接口地址：GSCloud文档3.13
     * http://ip:port/api/jg/fiaccbddata/v1.0/fiaccinterface/insertPzMidTable
     **/
    @SneakyThrows
    @Override
    public void execute(JobExecutionContext context) {
        //JBDC链接
        JdbcTemplate jdbcTemplate = SpringUtil.getBean(JdbcTemplate.class);

        try (Session oracleSession = DataSourceUtil.getLSOracleSession()) {
            String countSQL = sqlService.getGlDetailCountSQL();
            List<Map<String, Object>> list = jdbcTemplate.queryForList(countSQL);
            int count = Integer.parseInt(list.get(0).get("COUNT").toString());
            System.out.println("count条数为:" + count);
            if (count == 0) {
                return;
            } else {
                //批量处理
                for (int gl = 0; gl <= count / 2000; gl++) {
                    //传入变量 lastTime 最后抓取时间
                    //链接BIP数据库，查询出需要同步的数据，根据TS时间进行判断。
                    //TS从中间库表获取到最后一次更新时间，根据此时间进行增量查询推送；
                    //中间库日志表记录推送日志，成功、失败、返回信息等（备查）
                    //中间库记录最后推送数据的时间，根据时间进行下次查询的条件；
                    String methodName = "GLQuartz";
                    //JdbcTemplate jdbcTemplate = SpringUtil.getBean(JdbcTemplate.class);
                    //查询所有账套
                    List<Map<String, Object>> ALLZTLIST = orgService.selectAllGLCode(jdbcTemplate);
                    //2、根据ts时间戳，查询中间库gl_detail表数据，取100凭证号，定义一个批次，推送成功后，回写100个凭证的状态；
                    String selectSQL = sqlService.getGlDetailDataSql();
                    //查询数据，根据数据结果推送给GS浪潮
                    List<Map<String, Object>> maps = jdbcTemplate.queryForList(selectSQL);
                    //人员查询
                    String userList = "select CUSERID,USER_CODE,USER_NAME from  " + utilService.getOracle() + ".SM_USER" + utilService.getHZ();
                    List<Entity> userMaps = oracleSession.query(userList);
                    //拼装数据，推送给浪潮
                    String ids = "";
                    //批次号
                    String BATCHNO = "";
                    UUID uuid = UUID.randomUUID();
                    BATCHNO = String.valueOf(uuid);
                    //数据组装
                    if (maps.size() > 0) {
                        //按照公司CODE进行分组
                        Map<String, List<Map<String, Object>>> ztLIST = maps.stream().collect(Collectors.groupingBy(i -> i.get("GSZTCODE").toString(), LinkedHashMap::new, Collectors.toList()));
                        //循环分组集合
                        for (Map.Entry<String, List<Map<String, Object>>> zt : ztLIST.entrySet()) {
                            //按照ACCDOCCODE，PERIODCODE，YEAR进行分组
                            Map<String, List<Map<String, Object>>> voucherid = zt.getValue().stream().collect(Collectors.groupingBy(i -> i.get("ACCDOCCODE") + "," + i.get("PERIODCODE") + "," + i.get("YEAR"), LinkedHashMap::new, Collectors.toList()));
                            String logTS = "";
                            //json拼装
                            String GsJson = "";
                            GsJson += "[";
                            //字符串拼接
                            String idStrs = "";
                            //循环凭证集合
                            for (Map.Entry<String, List<Map<String, Object>>> objectListEntry : voucherid.entrySet()) {
                                //部门
                                String DEPTID = "";
                                //RELATEDORGID	往来单位编号
                                String RELATEDORGID = "";
                                //ACCEMPLOYEEID	核算人员编号
                                String ACCEMPLOYEEID = "";
                                List<Map<String, Object>> value = objectListEntry.getValue();
                                System.out.println("分录条数：" + value.size());
                                for (Map<String, Object> gSmap : value) {
                                    //字符串拼接
                                    String LYPZID = gSmap.get("LYPZID").toString();
                                    if (!idStrs.contains(LYPZID)) {
                                        idStrs += "'" + LYPZID + "',";
                                    }
                                    //获取ID查询辅助核算项
                                    String ASSID = (String) gSmap.get("ASSID");
                                    //根据ID查询
                                    String FZSQL = sqlService.getGlDocFreeMapSql(ASSID);
                                    //执行sql
                                    List<Entity> fzQuery = oracleSession.query(FZSQL);
                                    //判断辅助核算是否有值
                                    String ISHAVEFZ = "0";
                                    //辅助核算拼装，最后需要拼接道，参数中
                                    String GsJsonFZ = "";
                                    if (fzQuery.size() > 0) {
                                        ISHAVEFZ = "1";
                                        //部门赋值 DEPTID   核算部门编号
                                        String yynumSQL = "SELECT CAST(NUM AS CHAR) AS NUM,TABLENAME,TABLEKEY,CODEKEY,NAMEKEY,FREEKEY FROM " + utilService.getGSYY() + ".FREEMAP WHERE istrue = 'DEPT'";
                                        List<Map<String, Object>> deptMaps = jdbcTemplate.queryForList(yynumSQL);
                                        //往来单位赋值 RELATEDORGID	往来单位编号
                                        String wlnumSQL = "SELECT CAST(NUM AS CHAR) AS NUM,TABLENAME,TABLEKEY,CODEKEY,NAMEKEY,FREEKEY FROM " + utilService.getGSYY() + ".FREEMAP WHERE istrue = 'CANDS'";
                                        List<Map<String, Object>> wlMaps = jdbcTemplate.queryForList(wlnumSQL);
                                        //人员赋值  ACCEMPLOYEEID	核算人员编号
                                        String rynumSQL = "SELECT CAST(NUM AS CHAR) AS NUM,TABLENAME,TABLEKEY,CODEKEY,NAMEKEY,FREEKEY FROM " + utilService.getGSYY() + ".FREEMAP WHERE istrue = 'PERSON'";
                                        List<Map<String, Object>> ryMaps = jdbcTemplate.queryForList(rynumSQL);
                                        //循环辅助核算
                                        for (Map<String, Object> fzmap : fzQuery) {
                                            //部门
                                            if (!ObjectUtils.isEmpty(fzmap.get(deptMaps.get(0).get("FREEKEY"))) && !fzmap.get(deptMaps.get(0).get("FREEKEY")).equals("NN/A")) {
                                                //转换code
                                                String pkToCode = "SELECT " + deptMaps.get(0).get("CODEKEY") + " AS CODE FROM " + utilService.getOracle() + "." + deptMaps.get(0).get("TABLENAME") + utilService.getHZ() + " WHERE " + deptMaps.get(0).get("TABLEKEY") + " ='" + fzmap.get(deptMaps.get(0).get("FREEKEY")) + "'";

                                                List<Entity> DEPTCODE = oracleSession.query(pkToCode);
                                                // 判断是否有部门，没有赋值为WU
                                                if (ObjectUtils.isEmpty(DEPTCODE)) {
                                                    DEPTID = "wu";
                                                } else {
                                                    DEPTID = gSmap.get("YYZTCODE") + (String) DEPTCODE.get(0).get("CODE");
                                                }
                                            }
                                            //往来单位
                                            if (!ObjectUtils.isEmpty(fzmap.get(wlMaps.get(0).get("FREEKEY"))) && !fzmap.get(wlMaps.get(0).get("FREEKEY")).equals("NN/A")) {
                                                //转换code
                                                String wlpkToCode = "SELECT '03$'||CS.PK_CUST_SUP||CS.CODE AS CODE FROM " + utilService.getOracle() + "." + wlMaps.get(0).get("TABLENAME") + utilService.getHZ() + " CS  WHERE " + wlMaps.get(0).get("TABLEKEY") + " ='" + fzmap.get(wlMaps.get(0).get("FREEKEY")) + "'";

                                                List<Entity> WLCODE = oracleSession.query(wlpkToCode);
                                                //判断是否有往来单位，没有赋值为WU
                                                if (ObjectUtils.isEmpty(WLCODE.get(0).get("CODE"))) {
                                                    RELATEDORGID = "wu";
                                                } else {
                                                    String GSCODE = "";
                                                    for (Map<String, Object> ALLZTOBJ : ALLZTLIST) {
                                                        if (ALLZTOBJ.get("yyztCode").toString().equals(gSmap.get("YYZTCODE").toString())) {
                                                            GSCODE = ALLZTOBJ.get("gsCode").toString();
                                                        } else {

                                                        }
                                                    }
                                                    //将$替换为 GSCODE
                                                    RELATEDORGID = WLCODE.get(0).get("CODE").toString().replace("$", GSCODE);
                                                }
                                            }
                                            //人员辅助核算
                                            if (!ObjectUtils.isEmpty(fzmap.get(ryMaps.get(0).get("FREEKEY"))) && !fzmap.get(ryMaps.get(0).get("FREEKEY")).equals("NN/A")) {
                                                //转换code
                                                String rypkToCode = "SELECT " + ryMaps.get(0).get("CODEKEY") + " AS CODE FROM " + utilService.getOracle() + "." + ryMaps.get(0).get("TABLENAME") + utilService.getHZ() + " WHERE " + ryMaps.get(0).get("TABLEKEY") + " ='" + fzmap.get(ryMaps.get(0).get("FREEKEY")) + "'";

                                                List<Entity> RYCODE = oracleSession.query(rypkToCode);
                                                //如果没有人员则赋值为WU
                                                if (ObjectUtils.isEmpty(RYCODE)) {
                                                    ACCEMPLOYEEID = "wu";
                                                } else {
                                                    ACCEMPLOYEEID = gSmap.get("YYZTCODE") + (String) RYCODE.get(0).get("CODE");
                                                }
                                            }
                                            //有辅助的加入一个list   循环取值
                                            String keyValue = "";
                                            for (Map.Entry<String, Object> entry : fzmap.entrySet()) {
                                                String key = entry.getKey().toUpperCase();
                                                keyValue = (String) entry.getValue();
                                                //如果keyValue不为空，则匹配值
                                                if (!ObjectUtils.isEmpty(keyValue) && !keyValue.equals("NN/A")) {
                                                    String getFreeMap = "SELECT NUM,TABLENAME,TABLEKEY,CODEKEY,NAMEKEY,FREEKEY FROM " + utilService.getGSYY() + ".FREEMAP WHERE FREEKEY = '" + key + "' AND istrue NOT IN ('DEPT','PERSON','CANDS')";
                                                    List<Map<String, Object>> fzObjMap = jdbcTemplate.queryForList(getFreeMap);
                                                    if (fzObjMap.size() > 0) {
                                                        //  System.out.println("NUM"+fzObjMap.get(0).get("NUM"));
                                                        String feenum = String.valueOf(fzObjMap.get(0).get("NUM"));
                                                        if (fzObjMap.size() > 0) {
                                                            if (!ObjectUtils.isEmpty(feenum)) {
                                                                //转换code
                                                                String fzpkToCode = "SELECT " + fzObjMap.get(0).get("CODEKEY") + " AS CODE FROM " + utilService.getOracle() + "." + fzObjMap.get(0).get("TABLENAME") + utilService.getHZ() + " WHERE " + fzObjMap.get(0).get("TABLEKEY") + " ='" + keyValue + "'";

                                                                //核算核算数据编号
                                                                List<Entity> FZCODE = oracleSession.query(fzpkToCode);
                                                                if (ObjectUtils.isEmpty(FZCODE)) {
                                                                    keyValue = "wu";
                                                                } else {
                                                                    String GSCODE = "";
                                                                    for (Map<String, Object> ALLZTOBJ : ALLZTLIST) {
                                                                        if (ALLZTOBJ.get("yyztCode").toString().equals(gSmap.get("YYZTCODE").toString())) {
                                                                            GSCODE = ALLZTOBJ.get("gsCode").toString();
                                                                        }
                                                                    }
                                                                    keyValue = GSCODE + keyValue + (String) FZCODE.get(0).get("CODE");
                                                                }
                                                                keyValue = SafeStringUtils.escapeSpecialChars(keyValue);
                                                                //拼接参数
                                                                if (Integer.parseInt(feenum) < 10) {
                                                                    GsJsonFZ += "\"SPECATEID0" + feenum + "\": \"" + keyValue + "\",\n";
                                                                } else {
                                                                    GsJsonFZ += "\"SPECATEID" + feenum + "\": \"" + keyValue + "\",\n";
                                                                }
                                                            }

                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    } else {

                                    }
                                    String YYKMTX = ObjectUtils.isEmpty(gSmap.get("YYKMTX")) ? "" : gSmap.get("YYKMTX").toString();
                                    String ACCTITLECODE = ObjectUtils.isEmpty(gSmap.get("ACCTITLECODE")) ? "" : gSmap.get("ACCTITLECODE").toString();
                                    String YYCODE = ObjectUtils.isEmpty(gSmap.get("YYCODE")) ? "" : gSmap.get("YYCODE").toString();

                                    //查询科目辅助核算，比对是否有需要赋空的值,查询辅助核算项
                                    String kmfzSQL = sqlService.getGlDetailkmfzSql(YYKMTX, ACCTITLECODE, YYCODE);
                                    List<Entity> kmfzQuery = oracleSession.query(kmfzSQL);

                                    if (kmfzQuery.size() > 0) {
                                        //根据fzcode查询对应的GS辅助编码，给编码赋值wu
                                        for (Map<String, Object> kmfzEntity : kmfzQuery) {
                                            //查询科目的辅助核算
                                            String gsfzCode = "select gscode,istrue from " + utilService.getGSYY() + ".freemap where doccode = '" + kmfzEntity.get("fzcode") + "'";
                                            List<Map<String, Object>> fzObjMap = jdbcTemplate.queryForList(gsfzCode);
                                            //判断是否有辅助核算
                                            if (!ObjectUtils.isEmpty(fzObjMap)) {
                                                for (Map<String, Object> map : fzObjMap) {
                                                    if (map.get("istrue").toString().equals("DEPT")) {//部门
                                                        if (ObjectUtils.isEmpty(DEPTID)) {
                                                            DEPTID = "wu";
                                                        }
                                                    } else if (map.get("istrue").toString().equals("PERSON")) {//人员
                                                        if (ObjectUtils.isEmpty(ACCEMPLOYEEID)) {
                                                            ACCEMPLOYEEID = "wu";
                                                        }
                                                    } else if (map.get("istrue").toString().equals("CANDS")) {//往来
                                                        if (ObjectUtils.isEmpty(RELATEDORGID)) {
                                                            RELATEDORGID = "wu";
                                                        }
                                                    } else if (map.get("istrue").toString().equals("NO")) {
                                                        //科目辅助核算
                                                        int gscode = Integer.parseInt(map.get("gscode").toString());
                                                        String keyStr = "\"SPECATEID" + gscode + "\"";
                                                        if (GsJsonFZ.contains(keyStr)) {

                                                        } else {
                                                            GsJsonFZ += "\"SPECATEID" + gscode + "\": \"wu\",\n";
                                                        }
                                                    }
                                                }

                                            }
                                        }
                                    }
                                    //freeMapList去重
                                    // ids += "'" + gSmap.get("ID") + "',";
                                    ids += gSmap.get("ID") + ",";
                                    //制单人
                                    String MAKERCODE = gSmap.get("GSCODE").toString() + gSmap.get("MAKERCODE").toString();
                                    String AUDITORCODE = "";
                                    String BOOKERCODE = "";
                                    String CASHIERCODE = "";
                                    for (Map<String, Object> userMap : userMaps) {
                                        //审核人
                                        if (!ObjectUtils.isEmpty(gSmap.get("AUDITORCODE"))) {
                                            if (userMap.get("CUSERID").toString().equals(gSmap.get("AUDITORCODE"))) {
                                                AUDITORCODE = gSmap.get("GSCODE").toString() + userMap.get("USER_CODE");
                                            }
                                        }
                                        //出纳
                                        if (!ObjectUtils.isEmpty(gSmap.get("BOOKERCODE"))) {
                                            if (userMap.get("CUSERID").toString().equals(gSmap.get("BOOKERCODE"))) {
                                                BOOKERCODE = gSmap.get("GSCODE").toString() + userMap.get("USER_CODE");
                                            }
                                        }
                                        //记账人
                                        if (!ObjectUtils.isEmpty(gSmap.get("CASHIERCODE"))) {
                                            if (userMap.get("CUSERID").toString().equals(gSmap.get("CASHIERCODE"))) {
                                                CASHIERCODE = gSmap.get("GSCODE").toString() + userMap.get("USER_CODE");
                                            }
                                        }
                                    }
                                    //判断是否为外币辅助核算
//                                    String bzStr = gSmap.get("FOREIGNCURRENCYID").toString();
//                                    if (!bzStr.equals("CNY")) {
//                                        ISHAVEFZ = "1";
//                                    }
                                    GsJson += "{" +
                                            "\"ID\": \"" + gSmap.get("MID") + "\",\n" +
                                            "\"ORGCODE\": \"" + gSmap.get("gsztCode") + "\",\n" +
                                            "\"ACCDOCCODE\": \"" + gSmap.get("ACCDOCCODE") + "\",\n" +
                                            "\"ACCDOCDATE\": \"" + gSmap.get("ACCDOCDATE") + "\",\n" +
                                            "\"ACCDOCTYPECODE\": \"" + gSmap.get("ACCDOCTYPECODE") + "\",\n" +
                                            "\"PERIODCODE\": \"" + gSmap.get("PERIODCODE") + "\",\n" +
                                            "\"NUMBEROFATTCH\": \"" + gSmap.get("NUMBEROFATTCH") + "\",\n" +
                                            "\"YEAR\": \"" + gSmap.get("YEAR") + "\",\n" +
                                            "\"MAKERCODE\": \"" + MAKERCODE + "\",\n" +
                                            "\"OPERATORCODE \": \"" + gSmap.get("OPERATORCODE") + "\",\n" +
                                            "\"SECRETLEVEL\": \"" + gSmap.get("SECRETLEVEL") + "\",\n" +
                                            "\"APPROVERCODE\": \"" + gSmap.get("APPROVERCODE") + "\",\n" +
                                            "\"AUDITORCODE\": \"" + AUDITORCODE + "\",\n" +
                                            "\"BOOKERCODE\": \"" + BOOKERCODE + "\",\n" +
                                            "\"CASHIERCODE\": \"" + CASHIERCODE + "\",\n" +
                                            "\"ACCMANAGERCODE\": \"" + gSmap.get("ACCMANAGERCODE") + "\",\n" +
                                            "\"ISAUDIT\": \"" + gSmap.get("ISAUDIT") + "\",\n" +
                                            "\"ISBOOK\": \"" + gSmap.get("ISBOOK") + "\",\n" +
                                            "\"ISVOID\": \"" + gSmap.get("ISVOID") + "\",\n" +
                                            "\"ISAPPROVED\": \"" + gSmap.get("ISAPPROVED") + "\",\n" +
                                            "\"EXTERNALDOC\": \"" + gSmap.get("ACCDOCCODE") + "\",\n" +
                                            "\"ISREADYONLY\": \"" + gSmap.get("ISREADYONLY") + "\",\n" +
                                            "\"CREATOR\": \"" + gSmap.get("CREATOR") + "\",\n" +
                                            "\"CREATETIME\": \"" + gSmap.get("CREATETIME") + "\",\n" +
                                            "\"LASTMODIFIER\": \"" + gSmap.get("LASTMODIFIER") + "\",\n" +
                                            "\"LASTMODIFIEDTIME\": \"" + gSmap.get("LASTMODIFIEDTIME") + "\",\n" +
                                            "\"SUMMARY\": \"" + gSmap.get("SUMMARY").toString().replace("\"", "").replace("\\”", "") + "\",\n" +
                                            "\"ACCENTRYCODE\": \"" + gSmap.get("ACCENTRYCODE") + "\",\n" +
                                            "\"ACCTITLECODE\": \"" + gSmap.get("ACCTITLECODE") + "\",\n" +
                                            "\"DOCENTRYAMOUNT\": " + gSmap.get("DOCENTRYAMOUNT") + ",\n" +
                                            "\"LENDINGDIRECTION\": \"" + gSmap.get("LENDINGDIRECTION") + "\",\n" +
                                            "\"DEPTID\": \"" + DEPTID + "\",\n" +
                                            "\"RELATEDORGID\": \"" + RELATEDORGID + "\",\n" +
                                            "\"ACCEMPLOYEEID\": \"" + ACCEMPLOYEEID + "\",\n" +
                                            "\"FOREIGNCURRENCYID\": \"" + gSmap.get("FOREIGNCURRENCYID") + "\",\n" +
                                            "\"QUANTITY\": " + gSmap.get("QUANTITY") + ",\n" +
                                            "\"UNITPRICE\": " + gSmap.get("UNITPRICE") + ",\n" +
                                            "\"FOREIGNCURRENCY\": " + gSmap.get("FOREIGNCURRENCY") + ",\n" +
                                            "\"EXCHANGERATE\": " + gSmap.get("EXCHANGERATE") + ",\n" +
                                            "\"ANCILLARYAMOUNT\": " + gSmap.get("ANCILLARYAMOUNT") + ",\n" +
                                            "\"BIZDATE\": \"" + gSmap.get("BIZDATE") + "\",\n" +
                                            "\"BIZCODE\": \"" + gSmap.get("BIZCODE") + "\",\n" +
                                            "\"SETTLEMENT\": \"" + gSmap.get("SETTLEMENT") + "\",\n" +
                                            "\"APPLICATION\": \"" + gSmap.get("APPLICATION") + "\",\n";
                                    //根据辅助核算判断
                                    GsJson += GsJsonFZ;
                                    GsJson += "\"DATASTAUS\": \"" + gSmap.get("DATASTAUS") + "\",\n" +
                                            "\"ISIMPORTED\": \"" + gSmap.get("ISIMPORTED") + "\",\n" +
                                            "\"BATCHNO\": \"" + BATCHNO + "\",\n" +
                                            "\"REFERENCEID\": \"" + gSmap.get("REFERENCEID") + "\",\n" +
                                            "\"LYPZID\": \"" + gSmap.get("LYPZID") + "\",\n" +
                                            "\"FZCODE\": \"" + gSmap.get("FZCODE") + "\"," +
                                            //"\"DOCENTRYAMOUNTYB\": " + gSmap.get("DOCENTRYAMOUNT") + "," +
                                            "\"DOCENTRYAMOUNTYB\": " + gSmap.get("FOREIGNCURRENCY") + "," +
                                            // "\"ISHAVEFZ\": \"" + ISHAVEFZ + "\"" +
                                            "\"ISHAVEFZ\": \"" + "1" + "\"" +
                                            "},";
                                    //调用GS接口，推送给GS浪潮，获取返回值;
                                    logTS = (String) gSmap.get("TS");
                                }
                            }
                            //去掉拼接的最后一个字符
                            GsJson = GsJson.substring(0, GsJson.lastIndexOf(','));
                            GsJson = GsJson.replace("null", "");
                            GsJson += "]";

                            //去掉拼接的最后一个字符
                            idStrs = idStrs.substring(0, idStrs.lastIndexOf(','));
                            //推送凭证
                            //1、推送凭证

                            /*GsJson = GsJson.replace("\\", "\\\\")
                                    .replace("'", "\\\\'")
                                    .replace("‘", "\\\\‘")
                                    .replace("/", "\\\\/")
                                    .replace("%", "\\\\%")
                                    .replace("&", "\\\\&")
                                    .replace("\r\n", "\\r\\n")
                                    .replace("\\\\", "\\")  // 反斜杠
                                    .replace("\n", "")   // 换行符
                                    .replace("\r", "")   // 回车符
                                    .replace("\t", "")   // 制表符
                                    .replace("\\\"", "\"")  // 双引号
                                    .replace("\\'", "'");   // 单引号*/
                            // System.out.println("凭证JSON"+GsJson);
                            StopWatch st = new StopWatch();
                            System.out.println(methodName + "开始时间：" + LocalDateTime.now());
                            st.start();
                            String gsUrl = IP + ":" + PORT + "/api/jg/gl/v1.0/fiaccinterface/insertPzMidTable";
                            String returnMSG = HttpRequest.post(gsUrl)
                                    .header("Content-Type", "application/json")
                                    .header("Accept-Language", "zh-CHS")
                                    .header("X-ECC-Current-Tenant", ECC)
                                    .header("Authorization", Bearer).timeout(200000)
                                    .body(GsJson).execute().body();
                            System.out.println(methodName + "凭证返回值" + returnMSG);
                            st.stop();
                            System.out.println(methodName + "结束时间：" + LocalDateTime.now());
                            System.out.println(methodName + "接口耗时：" + st.getTotalTimeMillis() + "ms");
                            if (!returnMSG.isEmpty()) {
                                GsJson = SafeStringUtils.escapeForSql(GsJson);
                                returnMSG = returnMSG.replace("\'", "\\''")
                                        // .replace("'", "&#39;")
                                        .replace("/", "\\\\/")
                                        .replace("%", "\\\\%")
                                        //.replace("_", "\\_")
                                        .replace("&", "\\\\&")
//                            .replace("\\\\", "\\")  // 反斜杠
//                            .replace("\\n", "\n")   // 换行符
//                            .replace("\\r", "\r")   // 回车符
//                            .replace("\\t", "\t")   // 制表符
//                            .replace("\\\"", "\"")  // 双引号
//                            .replace("\\'", "'");   // 单引号;
//                    .replace(">", "&gt;")
//                    .replace("<", "&lt;")
//                    .replace(" ", "&nbsp;")
//                    .replace("\"", "&quot;")
//                    .replace("\'", "&#39;")
                                        .replace("\\", "\\\\")
                                        .replace("\n", "\\n")
                                        .replace("\r", "\\r")
                                        .replace("\r\n", "\\r\\n");

                                String logInsert = "";
                                Boolean success = false;
                                if (returnMSG.contains("Code")) {
                                    //写入日志表
                                    int loginsert = loginfo.loginfo(jdbcTemplate, methodName, LocalDateTime.now().toString(), "数据返回异常,【" + returnMSG + "】返回值为空！！！", GsJson, returnMSG, "", ids, gsUrl, logTS);
                                    if (loginsert > 0) {
                                        System.out.println("日志写入成功！！");
                                    } else {
                                        System.out.println("日志写入失败！！");
                                    }

                                } else {
                                    //System.out.println("凭证返回值" + returnMSG);
                                    JSONArray returnList = JSONArray.parseArray(returnMSG);
                                    //成功
                                    String yyids = "";
                                    String updateVoucher = "BEGIN\n";
                                    //状态保存
                                    for (int y = 0; y < returnList.size(); y++) {
                                        JSONObject returnObj = returnList.getJSONObject(y);
                                        if (ObjectUtils.isEmpty(returnObj.get("code")) && ("").equals(returnObj.get("code"))) {
                                            System.out.println("进入异常方法");
                                            //写入日志表
                                            int loginsert = loginfo.loginfo(jdbcTemplate, methodName, LocalDateTime.now().toString(), "数据返回异常", GsJson, returnMSG, "", ids, gsUrl, logTS);
                                            if (loginsert > 0) {
                                                System.out.println("日志写入成功！！");
                                            } else {
                                                System.out.println("日志写入失败！！");
                                            }
                                            //失败不执行
                                            success = false;
                                        } else if ("0".equals(returnObj.get("code").toString())) {
                                            success = true;
                                            //修改数据表业务推送状态，标记凭证已推送\回写推送批次
                                            String gsid = (String) returnObj.get("id");
                                            yyids += gsid + ",";
                                            //失败
                                        } else if ("1".equals(returnObj.get("code").toString())) {
                                            success = false;
                                            System.out.println("进入失败方法");
                                            //写入日志表
                                            if (y > 0) {
                                                GsJson = BATCHNO;
                                                returnMSG = "失败";
                                            }
                                            int loginsert = loginfo.loginfo(jdbcTemplate, methodName, LocalDateTime.now().toString(), "失败", GsJson, returnMSG, "", ids, gsUrl, logTS);
                                            if (loginsert > 0) {
                                                System.out.println("日志写入成功！！");
                                            } else {
                                                System.out.println("日志写入失败！！");
                                            }
                                            //失败不执行

                                        } else {
                                            System.out.println("进入异常其他方法");
                                            //写入日志表
                                            int loginsert = loginfo.loginfo(jdbcTemplate, methodName, LocalDateTime.now().toString(), "数据返回异常", GsJson, returnMSG, "", ids, gsUrl, logTS);
                                            if (loginsert > 0) {
                                                System.out.println("日志写入成功！！");
                                            } else {
                                                System.out.println("日志写入失败！！");
                                            }
                                            //失败不执行
                                            success = false;
                                        }
                                    }

                                    if (success) {
                                        //String batchSql = "update " + utilService.getGSYY() + ".GL_DETAIL SET PUSHSTATUS = '1', BATCHNO = '" + BATCHNO + "'  WHERE LYPZID IN ( SELECT LYPZID from " + utilService.getGSYY() + ".gs_push_100 )";
                                        String batchSql = "update " + utilService.getGSYY() + ".GL_DETAIL SET PUSHSTATUS = '1', BATCHNO = '" + BATCHNO + "'  WHERE LYPZID IN (" + idStrs + ")";
                                        //   System.out.println("执行SQL修改方法");
                                        int updateV = jdbcTemplate.update(batchSql);
                                        if (updateV > 0) {
                                            System.out.println("执行SQL修改方法---成功");
                                        } else {

                                            System.out.println("执行SQL修改方法---失败");
                                        }
                                        int loginsert = loginfo.loginfo(jdbcTemplate, methodName, LocalDateTime.now().toString(), "成功" + "信息详见RetrunMSG!!", GsJson, returnMSG, "", yyids, gsUrl, logTS);
                                        if (loginsert > 0) {
                                            System.out.println("日志写入成功！！");
                                        } else {
                                            System.out.println("日志写入失败！！");
                                        }
                                    }

                                }
                            } else {
                                System.out.println("进入异常2方法");
                                //写入日志表
                                int loginsert = loginfo.loginfo(jdbcTemplate, methodName, LocalDateTime.now().toString(), "数据返回异常,【" + returnMSG + "】返回值为空！！！", GsJson, returnMSG, "", "", gsUrl, logTS);
                                if (loginsert > 0) {
                                    System.out.println("日志写入成功！！");
                                } else {
                                    System.out.println("日志写入失败！！");
                                }
                            }
                        }
                    } else {
                        System.out.println(methodName + "：暂无新数据推送");
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
